const { Role } = require("../../models");
const { Op } = require("sequelize");
const { success, failure } = require("../../utils/responses");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");

/**
 * 分页数据列表
 * @param req
 * @param res
 */
exports.list = async (req, res) => {
  // 查询所有数据
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      order: [["id", "ASC"]],
      limit: pageSize,
      offset: offset,
    };
    // 模糊查询
    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }
    if (query.code) {
      condition.where = {
        code: {
          [Op.like]: `%${query.code}%`,
        },
      };
    }
    if (query.status) {
      condition.where = {
        status: {
          [Op.like]: `%${query.status}%`,
        },
      };
    }
    // 分页查询
    const { count, rows } = await Role.findAndCountAll(condition);
    // 返回
    success(res, "查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 分页数据列表
 * @param req
 * @param res
 */
exports.all = async (req, res) => {
  try {
    const { query } = paging(req);
    // 排序
    const condition = {
      raw: true, //只返回数据的参数 --默认返回包装类
    };
    // 模糊查询
    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }
    const rows = await Role.findAll(condition);
    // 返回
    success(res, "查询成功", rows);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 详情
 * @param req
 * @param res
 */
exports.details = async (req, res) => {
  try {
    const data = await getById(req);
    success(res, "查询成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 新增
 * @param req
 * @param res
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const data = await Role.create(body);
    success(res, "创建成功", data, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除
 * @param req
 * @param res
 */
exports.del = async (req, res) => {
  try {
    const data = await getById(req);
    await data.destroy();
    success(res, "删除成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新
 * @param req
 * @param res
 */
exports.update = async (req, res) => {
  try {
    const data = await getById(req);
    const body = filterBody(req);
    await data.update(body);
    success(res, "更新成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新 status
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.updateStatus = async (req, res) => {
  try {
    const data = await getById(req);
    const status = data.status === 1 ? 0 : 1;
    await data.update({ status });
    success(res, "更新成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新状态 menuId
 * @param req
 * @param res
 */
exports.updateMenuIds = async (req, res) => {
  try {
    const data = await getById(req);
    await data.update({ menuId: JSON.stringify(req.body.data) }); //删除
    success(res, "更新成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 获取角色管理--菜单-根据角色 id 查对应菜单
 * GET /getByIdMenuIds
 */
exports.getByIdMenuIds = async (req, res) => {
  try {
    const data = await getById(req);
    let list = [];
    if (data.menuId) {
      list = JSON.parse(data.menuId);
    }
    success(res, "查询成功", list);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 获取角色管理-权限-菜单权限-根据角色 id 查对应菜单
 * @param req
 * @param res
 */
exports.getRoleMenuIds = async (req, res) => {
  try {
    const data = await getById(req);
    let list = [];
    if (data.menuId) {
      list = JSON.parse(data.menuId);
    }
    success(res, "查询成功", list);
  } catch (error) {
    console.log(error);
    failure(res, error);
  }
};

/**
 * 获取当前
 * @param req
 * @returns {Promise<Model<any, any>>}
 */
async function getById(req) {
  const id = req.body.id || req.params.id || req.query.id;
  if (!id) {
    throw new NotFoundError(`ID: 参数错误`);
  }
  // 获取当前
  const data = await Role.findByPk(id);
  if (!data) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return data;
}

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {*}
 */
function filterBody(req) {
  return {
    name: req.body.name, //'角色名称',
    code: req.body.code, // 角色标识
    // status: 'number', // 状态,
    // menuId: 'string', // 角色ID
    remark: req.body.remark, // 备注
  };
}
